package com.shoesmail.service;

import com.shoesmail.filter.AccountBloomFilter;
import com.shoesmail.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：CDB
 * @description：账号生成
 * @date ：2025/9/16 22:11
 */
@Service
public class AccountGenericService {
    @Autowired
    private AccountBloomFilter accountBloomFilter;

    @Autowired
    private AccountMapper accountMapper;

    private final Random random = new Random();

    private final static int onceCount = 1000;


    private static ReentrantLock insertAccountLock = new ReentrantLock();
    private void generateAccount(int count) {
        List<Long> batch = new ArrayList<>();
        while (batch.size() < count) {
            long account = generateRandomAccount();
            if (accountBloomFilter.accountContain(account)){
                continue; // 可能重复
            }
            batch.add(account);
            accountBloomFilter.put(account); // 插入 Redis Bloom
        }
        accountMapper.insertAccount(batch); // 使用 INSERT IGNORE 防止万一冲突
    }

    private long generateRandomAccount() {
        int length = random.nextInt(2) + 10; // 10-12位
        StringBuilder sb = new StringBuilder();
        sb.append(random.nextInt(9) + 1); // 首位不能为0
        for (int i = 1; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return Long.parseLong(sb.toString());
    }

    //TODO 定时生成还是注册执行
    @Scheduled(fixedDelay = 30 * 60 * 1000)
    @Async
    public void needGenericAccount(){
        insertAccountLock.lock();
        try {
            long canUseAccount = accountMapper.getCanUseAccountSum();
            if(canUseAccount<100){
                generateAccount(onceCount);
            }
        } finally {
            insertAccountLock.unlock();
        }
    }
}
